package yannan.voiplock4ble;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.WindowManager;

import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.test.AbstractDaoTestLongPk;

import java.io.File;
import java.util.List;

import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.UnLoggedBaseActivity;
import yannan.voiplock4ble.bean.UserAccount;
import yannan.voiplock4ble.bean.VersionBean;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.daomanager.UserAccountDaoManager;
import yannan.voiplock4ble.eventbus.EventObject;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.service.DownLoadService;
import yannan.voiplock4ble.task.LoginTask;
import yannan.voiplock4ble.task.SearchNickNameFromPhone;
import yannan.voiplock4ble.utils.DeviceUtils;
import yannan.voiplock4ble.utils.PopShowUtils;

import static yannan.voiplock4ble.utils.PopShowUtils.COMMON_DIALOG_RIGHT;


/**
 * 说明：启动页Activity
 * 作者：mainTel
 * 时间：2016/8/19 11:48
 * 备注：
 */
@Content(R.layout.aciticy_splash)
public class SplashActivity extends UnLoggedBaseActivity {

    final static int GOTO_LOGIN = 1002;
    boolean isForce = false;// app更新是否为强制更新
    String appUrl;// app更新地址

    @Override
    public void initData() {
        MobclickAgent.openActivityDurationTrack(false);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); //虚拟按键透明
        //申请的权限
        requestPermssion(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_CONTACTS});
    }

    /**
     * 申请权限
     */
    private void requestPermssion(String[] permissionGroup) {
        requestRunTimePermssions(this, permissionGroup, new PermissionLister() {
            @Override
            public void grant() {
                getVersion();
            }

            @Override
            public void deny(final List<String> pStringList) {
                PopShowUtils.showCommonDialog(SplashActivity.this, "有权限没有同意，去同意？", "取消", "确定", true, new PopShowUtils.IDialogCommonListener() {
                    @Override
                    public void onClick(int direction) {
                        if (direction == PopShowUtils.COMMON_DIALOG_LEFT) {
                            finish();
                        } else if (direction == COMMON_DIALOG_RIGHT) {
                            requestPermssion(pStringList.toArray(new String[pStringList.size()]));
                        }
                    }
                });
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case GOTO_LOGIN:
                    jumpLoginOrMain();
                    break;
            }
        }
    };

    /**
     * 跳转页面s
     */
    private void jumpLoginOrMain() {
        if (DeviceUtils.isOnline(this)) {
            UserAccount account = DaoUtils.getDao(UserAccountDaoManager.class).selectFirst();
            if (account == null || (account.getUserPwd() != null && account.getUserPwd().equals(""))) {
                goToLogin();
            } else {
                LoginTask.create(SplashActivity.this, account.getUserAccount(), account.getUserPwd(), true, false).start();
            }
        } else {
            goToLogin();
        }
    }

    private void goToLogin() {
        Intent intent = new Intent();
        intent.setClass(mContext, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String msg) {
        if (msg.equals("closeLoginActivity"))
            finish();
    }

    /**
     * 检查更新
     */
    private void checkVersion(final int versionCode) {
        NetUtils.getNetworkService().checkAppVersion().enqueue(new NetworkCallBack<VersionBean>() {
            @Override
            public void onSuc(VersionBean resBody) {
                //有更新
                final Intent intent = new Intent(SplashActivity.this, DownLoadService.class);
                intent.putExtra("isForce", resBody.isForce);
                intent.putExtra("url", resBody.appUrl);
                appUrl = resBody.appUrl;
                if (resBody.verCode > versionCode) {
                    //1代表强制升级
                    isForce = resBody.isForce == 1;
                    if (resBody.isForce == 1) {
                        startService(intent);
                    } else {
                        if (resBody.verMessage == null || resBody.verMessage.equals("")) {
                            resBody.verMessage = "检测到更新，为了您更好的使用体验，请您选择升级app";
                        }
                        PopShowUtils.showCommonDialog(SplashActivity.this, resBody.verMessage,
                                "暂不升级", "立即升级", false,
                                new PopShowUtils.IDialogCommonListener() {
                                    @Override
                                    public void onClick(int direction) {
                                        if (direction == COMMON_DIALOG_RIGHT) {
                                            startService(intent);
                                        } else {
                                            handler.sendEmptyMessage(GOTO_LOGIN);
                                        }
                                    }
                                });
                    }
                } else {
                    //无需更新
                    handler.sendEmptyMessageDelayed(GOTO_LOGIN, 1000);
                }
            }

            @Override
            public void onFail(String msg) {
                //无更新
                handler.sendEmptyMessageDelayed(GOTO_LOGIN, 1000);
//                startService(new Intent(SplashActivity.this, DownLoadService.class));
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventObject msg) {
        if (msg.eventTag.equals(EventObject.UPDATEDOWNLOADAPKPROGRESS)) {
            //下载进度
            PopShowUtils.showDownLoadProgressDialog(this, (int) msg.eventObj, "正在下载");
        } else if (msg.eventTag.equals(EventObject.DOWNLOADCOMPELTE)) {
            //下载完成
            PopShowUtils.cacelDownLoadProgressDialog();
            autoInstallApk();
            finish();
        } else if (msg.eventTag.equals(EventObject.DOWNLOAD_FAILURE)) {
            PopShowUtils.cacelDownLoadProgressDialog();
            //下载失败

            PopShowUtils.showCommonDialog(this, "由于未知原因，下载失败了，是否重新下载?", "否", "是", false,
                    new PopShowUtils.IDialogCommonListener() {

                        @Override
                        public void onClick(int direction) {
                            if (direction == COMMON_DIALOG_RIGHT) { //重新下载
                                Intent intent = new Intent(SplashActivity.this, DownLoadService.class);
                                intent.putExtra("url", appUrl);
                                startService(intent);
                            } else {
                                if (isForce) { //如果是强制更新
                                    finish();
                                } else {
                                    handler.sendEmptyMessage(GOTO_LOGIN);
                                }
                            }
                        }
                    });
        }
    }


    /**
     * 自动安装
     */
    public void autoInstallApk() {
        finish();
        File newFile = new File(Environment.getExternalStorageDirectory() + "/vipLock", "test.apk");
        if (newFile.exists()) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setData(FileProvider.getUriForFile(this, "yannan.voiplock4ble.fileProvider", newFile));
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                intent.setDataAndType(Uri.fromFile(newFile), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            startActivity(intent);
        } else {
        }
    }

    /**
     * 获取本地的版本号，并开始更新
     */
    private void getVersion() {
        int versionCode = 1;
        try {
            versionCode = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
        checkVersion(versionCode);
    }
}
